package me.zhengjie.modules.web.service.chat.validate.impl;

import cn.hutool.core.date.DateUnit;
import me.zhengjie.modules.system.service.UserChatOrderService;
import me.zhengjie.modules.system.service.dto.UserChatOrderDto;
import me.zhengjie.modules.system.service.dto.UserChatOrderQueryCriteria;
import me.zhengjie.modules.web.domain.chat.BaiduChatResponse;
import me.zhengjie.modules.web.enums.OrderStatusEnum;
import me.zhengjie.modules.web.service.chat.validate.IReplayFeeValidate;
import me.zhengjie.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("FreeMonthValidate")
@Order(0)
public class FreeMonthValidate implements IReplayFeeValidate {

    @Autowired
    UserChatOrderService userChatOrderService;

    @Override
    public boolean validate(String openId, BaiduChatResponse response) {
        UserChatOrderQueryCriteria criteria = new UserChatOrderQueryCriteria();
        criteria.setOpenId(openId);
        criteria.setOrderStatus(OrderStatusEnum.Payed.getOrderStatus());
        Timestamp now = DateUtil.TimestampNow();
        Date replayEndTime = DateUtil.addDay(DateUtil.toDate(now.toLocalDateTime()), 100 * 365);
        List<Timestamp> replayEndTimeList = new ArrayList<>();
        replayEndTimeList.add(now);
        replayEndTimeList.add(DateUtil.dateConvertTimestamp(replayEndTime));
        criteria.setReplayEndTime(replayEndTimeList);
        List<UserChatOrderDto> orderList = userChatOrderService.queryAll(criteria);
        if(CollectionUtils.isEmpty(orderList)){
            return false;
        }
        UserChatOrderDto order = orderList.get(0);
        long day =  cn.hutool.core.date.DateUtil.between(now,order.getReplayEndTime(), DateUnit.DAY,false);
        if(day <= 0){
            return false;
        }
        response.setSurplusTimes(day);
        response.setSurplusUnit(2);
        return true;
    }

    @Override
    public boolean get(String openId, BaiduChatResponse response) {
        return validate(openId,response);
    }
}
